package com.houdoudou.customer.buy;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Branch;
import com.houdoudou.bean.Car;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Product;
import com.houdoudou.bean.Supplier;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.AsynImageLoader;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.HorizontalListView;
import com.houdoudou.customer.sqlite.CarDao;
import com.houdoudou.customer.sqlite.CarManagement;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;

import android.widget.TextView;

public class FrgProductDetail extends Fragment{
  
//////一下数据用于加入购物车
	
	
    Context parentContext; 
	TextView branch1,branch2,branch3,branch4,branch5,branch6;
	TextView price,num,branch_incar;
	TextView detail,hint1,hint2,hint3;
	TextView clear_saved;
    LinearLayout lt_branch,lt_branch1,lt_branch2,branches_saved;
	Button increase,decrease;
	ListView listview_showsaved;
	HorizontalListView picListView;
	static LinearLayout lt_showsaved;
	static LinearLayout lt_shadow;
	static Button addToCar;
	SavedBranchListAdapter savedListAdapter;
	PicListAdapter picListAdapter;
	ScrollView scrollcontent;
	ImageView pic;
	AsynImageLoader imageLoader;
	JSONObject carJO=new JSONObject();
//	HorizontalListView listview_branch;
//	BranchListAdapter myBranchAdapter;
	
    
	View.OnClickListener myOnclickListener,branchOnclickListener;
	JSONObject productJO=new JSONObject();
	JSONArray Saved_Branch_JA=new JSONArray();
	int BRANCH_SIZE=0;
	
	public static boolean isShowSaved=false;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//return super.onCreateView(inflater, container, savedInstanceState);
		View view=inflater.inflate(R.layout.frg_detail_productact, container, false);
		parentContext=getActivity();
		imageLoader= new AsynImageLoader(getActivity());
		init_listener();
		init_component(view);
		
	
		branch1.performClick();
	//	myBranchAdapter= new BranchListAdapter(parentContext);
	//	listview_branch.setAdapter(myBranchAdapter);
	//	myBranchAdapter.notifyDataSetChanged();
	 
	    
	     savedListAdapter=new SavedBranchListAdapter(getActivity());
	     listview_showsaved.setAdapter(savedListAdapter);
	     
	     picListAdapter= new PicListAdapter(getActivity());
	     picListView.setAdapter(picListAdapter);
	     refresh_saved();
		return view;
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	@Override
	public void setArguments(Bundle bundle) {
		// TODO Auto-generated method stub
		
		productJO=JSONObject.fromObject(bundle.getString("product"));
		//productJO.put("Arrive_Time",ShopAct.Arrive_Time);
		//System.out.print("------------------"+productJO.toString());
		 productJO.put(Car.NUMBER, 1);
		 productJO.put(Car.BRANCH, productJO.getJSONArray("branches").getJSONObject(0).getInt(Branch.ID));
		BRANCH_SIZE=productJO.getJSONArray("branches").size(); 
		System.out.print("---------BRANCH_SIZE---------"+BRANCH_SIZE);
		carJO.put(Car.MACHINE, Constant.machineJO.getInt(Machine.ID));
		carJO.put(Car.TIMEFLAG, ShopAct.supplierJO.getInt(Car.TIMEFLAG));
		carJO.put(Car.SUPPLIER, ShopAct.supplierJO.getString(Supplier.TELNUM));
		carJO.put(Car.PRODUCT,productJO.getInt(Product.ID) );
		carJO.put(Car.NUMBER, 1);
		super.setArguments(bundle);
	}
	
	private void init_component(View view){
	
	 //   listview_branch= (HorizontalListView) view. findViewById(R.id.listview_branch_frg_productdetail);    
	 //   cancel_addtopakege.setOnClickListener(myOnclickListener);
	//	confirm_addtopakege.setOnClickListener(myOnclickListener);
		
		///--------------------初始化branch-------------------------/
	branch1= (TextView) view.findViewById(R.id.tv_branch1_frg_productdetail);
	branch2= (TextView) view.findViewById(R.id.tv_branch2_frg_productdetail);
	branch3= (TextView) view.findViewById(R.id.tv_branch3_frg_productdetail);
	branch4= (TextView) view.findViewById(R.id.tv_branch4_frg_productdetail);
	branch5= (TextView) view.findViewById(R.id.tv_branch5_frg_productdetail);
	branch6= (TextView) view.findViewById(R.id.tv_branch6_frg_productdetail);
	lt_branch=(LinearLayout) view.findViewById(R.id.ltbranch_frg_productdetail);
	lt_branch1=(LinearLayout) view.findViewById(R.id.ltbranch_line1_frg_productdetail);
	lt_branch2=(LinearLayout) view.findViewById(R.id.ltbranch_line2_frg_productdetail);
	
	branch1.setOnClickListener(branchOnclickListener);
	branch2.setOnClickListener(branchOnclickListener);
	branch3.setOnClickListener(branchOnclickListener);
	branch4.setOnClickListener(branchOnclickListener);
	branch5.setOnClickListener(branchOnclickListener);
	branch6.setOnClickListener(branchOnclickListener);
	
	if(BRANCH_SIZE<6) { branch6.setVisibility(View.GONE);	}	
	if(BRANCH_SIZE<5) { branch5.setVisibility(View.GONE); }	
	if(BRANCH_SIZE<4) { branch4.setVisibility(View.GONE); 
	                  lt_branch2.setVisibility(View.GONE);}	
	if(BRANCH_SIZE<3) { branch3.setVisibility(View.GONE); }
	if(BRANCH_SIZE<2) { branch2.setVisibility(View.GONE);branch1.setVisibility(View.GONE);   
	                  lt_branch.setVisibility(View.GONE);}
	
	if(BRANCH_SIZE<1) {simple_aleart("数据有问题", "规格数据为空");}	
	
	if(BRANCH_SIZE>=2) {branch1.setText(productJO.getJSONArray("branches").getJSONObject(0).getString(Branch.NAME));
	                   branch2.setText(productJO.getJSONArray("branches").getJSONObject(1).getString(Branch.NAME));}
	if(BRANCH_SIZE>=3){branch3.setText(productJO.getJSONArray("branches").getJSONObject(2).getString(Branch.NAME));}
	if(BRANCH_SIZE>=4){branch4.setText(productJO.getJSONArray("branches").getJSONObject(3).getString(Branch.NAME));}
	if(BRANCH_SIZE>=5){branch5.setText(productJO.getJSONArray("branches").getJSONObject(4).getString(Branch.NAME)); }
	if(BRANCH_SIZE>=6){branch6.setText(productJO.getJSONArray("branches").getJSONObject(5).getString(Branch.NAME)); }
	///--------------------初始化其余控件-------------------------/
    pic= (ImageView) view.findViewById(R.id.img_product_frg_productdetail);
	price=(TextView) view.findViewById(R.id.tv_branchprice_frg_productdetail);
	num=(TextView) view.findViewById(R.id.tv_branchnum_frg_productdetail);
	
	detail=(TextView) view.findViewById(R.id.tv_productdetail_frg_productdetail);
	hint1=(TextView) view.findViewById(R.id.tv_hint1_frg_productdetail);
	hint2=(TextView) view.findViewById(R.id.tv_hint2_frg_productdetail);
	hint3=(TextView) view.findViewById(R.id.tv_hint3_frg_productdetail);
	branch_incar=(TextView) view.findViewById(R.id.tv_incar_frg_productdetail);
	lt_showsaved= (LinearLayout) view.findViewById(R.id.lt_showsaved_frg_productdetail);
	listview_showsaved=(ListView) view.findViewById(R.id.listview_showsaved_frg_productdetail);
	lt_shadow=(LinearLayout) view.findViewById(R.id.lt_shadow_frg_productdetail);
	picListView=  (HorizontalListView) view.findViewById(R.id.hListView_product_frg_productdetail);
	
	increase=(Button) view.findViewById(R.id.btn_branchincrease_addtopakege_act_shop);
	decrease=(Button) view.findViewById(R.id.btn_branchdecrease_addtopakege_act_shop);
	addToCar=(Button) view.findViewById(R.id.btn_addtocar_frg_productdetail);
	branches_saved=(LinearLayout) view.findViewById(R.id.lt_saved_frg_productdetail);
	scrollcontent= (ScrollView) view.findViewById(R.id.sclView_frg_product_detail);
	clear_saved= (TextView) view.findViewById(R.id.tv_clear_showsavedtitle_frg_productdetail);
	
	imageLoader.showImageAsyn(pic, productJO.getString(Product.DIR)+"0.jpg", R.drawable.p3);
	detail.setText(productJO.getString(Product.DETAIL));
	hint1.setText("本品"+ShopAct.addresswords);
	hint2.setText("本品"+ShopAct.timewords);
	hint3.setText("本品"+ShopAct.noticewords);
	increase.setOnClickListener(myOnclickListener);
	decrease.setOnClickListener(myOnclickListener);
	addToCar.setOnClickListener(myOnclickListener);
	branches_saved.setOnClickListener(myOnclickListener);
	lt_shadow.setOnClickListener(myOnclickListener);
	clear_saved.setOnClickListener(myOnclickListener);
	
	
	
	lt_showsaved.setVisibility(View.GONE);
	lt_shadow.setVisibility(View.GONE);
	
	}
	
	private void init_listener(){
		myOnclickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v==increase){
					 productJO.put(Car.NUMBER,productJO.getInt(Car.NUMBER)+1);
					 carJO.put(Car.NUMBER,carJO.getInt(Car.NUMBER)+1);
					 refrsesh_frg_data();
				           }
				if(v==decrease){
					      if(productJO.getInt(Car.NUMBER)>1){
					      productJO.put(Car.NUMBER,productJO.getInt(Car.NUMBER)-1);
					      carJO.put(Car.NUMBER,carJO.getInt(Car.NUMBER)-1);
					      refrsesh_frg_data();}
				       }
				if(v==addToCar){
					CarDao carDao= new CarDao(getActivity());
				//	JSONObject check= carDao.queryOneBranch(productJO);
					JSONObject check= carDao.queryOneBranch(carJO);
					//已有产品，只是增加数量。
					if(check.getBoolean("success")){					
						// productJO.put(Car.NUMBER, productJO.getInt(Car.NUMBER)+check.getInt(Car.NUMBER));
						// carDao.updateOneRecord(productJO);
						check.put(Car.NUMBER, carJO.getInt(Car.NUMBER)+check.getInt(Car.NUMBER));
						carDao.updateOneRecord(check);
				
						 //没有就新增
					}else{
						 carDao.insert(carJO);
					}
					refresh_saved();
				}
				if(v==branches_saved){
				
				if(isShowSaved){
					hide_lt_saved();
				}else{
					lt_showsaved.setVisibility(View.VISIBLE);
					lt_shadow.setVisibility(View.VISIBLE);
					isShowSaved=true;
					addToCar.setClickable(false);
				 }
				 }
				if(v==lt_shadow){
					if(isShowSaved){
						hide_lt_saved();
					}
				}
			  if(v==clear_saved){
				  if(Saved_Branch_JA.size()>0){
				  new CarDao(getActivity()).deleteOneProduct(carJO);
				  refresh_saved();
				  }
			  }	
				
			}
		};
		
		branchOnclickListener=new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				clear_selected_branch();				
				int i=100;
				if(v==branch1) { 
					branch1.setBackgroundResource(R.drawable.branch_selected_style);
				       i=0;
					}
				if(v==branch2) { 
					branch2.setBackgroundResource(R.drawable.branch_selected_style);
					i=1;}
				if(v==branch3) { 
					branch3.setBackgroundResource(R.drawable.branch_selected_style);
					i=2;}
				if(v==branch4) { 
					branch4.setBackgroundResource(R.drawable.branch_selected_style);
					i=3;}
				if(v==branch5) { 
					branch5.setBackgroundResource(R.drawable.branch_selected_style);
					i=4;}
				if(v==branch6) { 
					branch6.setBackgroundResource(R.drawable.branch_selected_style);
					i=5;
					}
				if(i!=100){
				productJO.put(Car.BRANCH, productJO.getJSONArray("branches").getJSONObject(i).getInt(Branch.ID));
				carJO.put(Car.BRANCH, productJO.getJSONArray("branches").getJSONObject(i).getInt(Branch.ID));
				  }
				 refrsesh_frg_data();
				}
		};
		
	}
	public static void hide_lt_saved(){
		lt_showsaved.setVisibility(View.GONE);
		lt_shadow.setVisibility(View.GONE);
		isShowSaved=false;
		addToCar.setClickable(true);
	}
	
	private void clear_selected_branch(){
		
		branch1.setBackgroundResource(R.drawable.branch_unselected_style);
		branch2.setBackgroundResource(R.drawable.branch_unselected_style);
		branch3.setBackgroundResource(R.drawable.branch_unselected_style);
		branch4.setBackgroundResource(R.drawable.branch_unselected_style);
		branch5.setBackgroundResource(R.drawable.branch_unselected_style);
		branch6.setBackgroundResource(R.drawable.branch_unselected_style);
	}
	
	private void simple_aleart(String title,String message){
		 new AlertDialog.Builder(getActivity()).setTitle(title)
		 .setMessage(message).setPositiveButton("确定", null).show();
	}
	//刷新界面数据，只刷新 textView ,不会刷新 branch_selected
	private void refrsesh_frg_data(){
		 double branchPrice=0;
	        int branchID=carJO.getInt(Car.BRANCH);
	          for(int j=0;j<BRANCH_SIZE;j++){
	        	  if(productJO.getJSONArray("branches").getJSONObject(j).getInt(Branch.ID)==branchID){		        		
	        		  branchPrice=productJO.getJSONArray("branches").getJSONObject(j).getDouble(Branch.PRICE);
	        		  break;
	        	  }	          
                   }
	          
		price.setText("单价：￥"+branchPrice);
		num.setText("数量："+productJO.getInt(Car.NUMBER));
	
	}
	private void refresh_saved(){
		Saved_Branch_JA=new CarDao(getActivity()).queryByProduct(carJO);
	   
	  //这里要调用本地数据库。暂时先这样写好了。
	    int num = 0;
	    double money = 0;
	    for(int i=Saved_Branch_JA.size()-1;i>=0;i--){
	    	 double branchPrice=-1;
		        int branchID=Saved_Branch_JA.getJSONObject(i).getInt(Car.BRANCH);
		          for(int j=0;j<BRANCH_SIZE;j++){
		        	  if(productJO.getJSONArray("branches").getJSONObject(j).getInt(Branch.ID)==branchID){		        		
		        		  branchPrice=productJO.getJSONArray("branches").getJSONObject(j).getDouble(Branch.PRICE);
		        		  num+=Saved_Branch_JA.getJSONObject(i).getInt(Car.NUMBER);
		        		  money+=Saved_Branch_JA.getJSONObject(i).getInt(Car.NUMBER)*branchPrice;
		        		  break;
		        	  }	 }
		     if(branchPrice==-1){
		    	 new CarDao(getActivity()).deleteOneRecord(Saved_Branch_JA.getJSONObject(i));
		    	 Saved_Branch_JA.remove(i);}     
	    }
	    String temp="("+num+"份"+ money+"元)";
	  		branch_incar.setText(temp);
	   savedListAdapter.notifyDataSetChanged(); 
	}
	    
	class SavedBranchListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	public SavedBranchListAdapter(Context context) {
		
					
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}
	
	
	final class Zujian{  
	    public TextView product,branch,num,money,increase,decrease;  
      
    
   }   //end of Zujian

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		 return Saved_Branch_JA.size();  
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return Saved_Branch_JA.getJSONObject(position);  
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}
 
	@Override
	public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_branchsaved_frg_productdetail, null);  
	            
	            zj.branch=(TextView) convertView.findViewById(R.id.tv_branchname_list_frg_productdetail);
	            zj.num=(TextView) convertView.findViewById(R.id.tv_branchnum_list_frg_productdetail);
	            zj.money=(TextView) convertView.findViewById(R.id.tv_branchmoney_list_frg_productdetail);
	            zj.decrease=(TextView) convertView.findViewById(R.id.tv_decrease_list_frg_productdetail);
	            zj.increase=(TextView) convertView.findViewById(R.id.tv_increase_list_frg_productdetail);
	            convertView.setTag(zj);  
	            System.out.println("position----"+position+"------inflated");
	        }else{   System.out.println("position----"+position+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  		        						  
	        //绑定数据  
	     
	        String  branchName="";
	        double branchPrice=0;
	        int branchID=Saved_Branch_JA.getJSONObject(position).getInt(Car.BRANCH);
	          for(int i=0;i<BRANCH_SIZE;i++){
	        	  if(productJO.getJSONArray("branches").getJSONObject(i).getInt(Branch.ID)==branchID){
	        		  branchName=productJO.getJSONArray("branches").getJSONObject(i).getString(Branch.NAME);
	        		  branchPrice=productJO.getJSONArray("branches").getJSONObject(i).getDouble(Branch.PRICE);
	        		  break;
	        	  }
	          }
	        zj.branch.setText(branchName);
	        int Branch_Num=Saved_Branch_JA.getJSONObject(position).getInt(Car.NUMBER);
	        zj.num.setText(String.valueOf(Branch_Num)+"份");
	        double Money=branchPrice*Branch_Num;
	        zj.money.setText("￥"+String.valueOf(Money));
	        
	        zj.decrease.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int number=Saved_Branch_JA.getJSONObject(selectID).getInt(Car.NUMBER);
					if(number>1){
						JSONObject temp= Saved_Branch_JA.getJSONObject(selectID);
						temp.put(Car.NUMBER, temp.getInt(Car.NUMBER)-1);
						 new CarDao(context).updateOneRecord(temp);	
					}else{
						new CarDao(context).deleteOneRecord(Saved_Branch_JA.getJSONObject(selectID));
					}
					refresh_saved();
				  
				}
			});
            zj.increase.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stubcarDao.updateOneRecord(check);
					JSONObject temp= Saved_Branch_JA.getJSONObject(selectID);
					temp.put(Car.NUMBER, temp.getInt(Car.NUMBER)+1);
					 new CarDao(context).updateOneRecord(temp);				 
				    refresh_saved();
				  
				}
			});
	        return convertView;
           } 
      }// end Adapter
	
class PicListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	public PicListAdapter(Context context) {
		
					
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}
	
	
	final class Zujian{  
	    public ImageView pic;  
      
    
   }   //end of Zujian

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		 return productJO.getInt(Product.PICNUM);  
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return Saved_Branch_JA.getJSONObject(position);  
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}
 
	@Override
	public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_pic_frgdetail_actproduct, null);  
	            zj.pic=(ImageView) convertView.findViewById(R.id.img_list_pic_frgdetail_actproduct);          
	            convertView.setTag(zj);  	           
	        }else{  
	            zj=(Zujian)convertView.getTag();  
	        }  		        						  
	        //绑定数据  
	        imageLoader.showImageAsyn(zj.pic, productJO.getString(Product.DIR)+selectID+".jpg", R.drawable.p3);
	        return convertView;
           } 
      }// end Adapter 
}
